<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户模型
 *
 * @author www.dingwei.cn
 */

class MerchantUserModel extends MY_Model{
	
	public $tbUser = 'merchant';
	public $tbShop = 'merchant_shop';
	public $tbCat = 'merchant_category';
	public $tbSession = 'merchant_session';
	public $tbVerifyCode = 'merchant_verify_code';
	public $tbRankLog = 'merchant_rank_log';
	public $tbBusiness = 'merchant_business_time'; // 多时间段

    public $config = array(
        'gender' => array('1' => '保密','2' => '男','3' => '女'),
        'week' => array('1' => '周一','2' => '周二','3' => '周三','4' => '周四','5' => '周五','6' => '周六','7' => '周日'),
        'rank' => array('1' => '初级','2' => '中级','3' => '高级'),
        'shop_type' => array('1' => '送货上门','2' => '到店消费','3' => '送货上门,到店消费'),
        'shop_status' => array('1' => '失败','2' => '通过','3' => '审核中')
    );
    
    //商家活动图标
    public $SHOP_ICON = array(
			'd'=>'static/img/coupon_d.png',//代   
			'x'=>'static/img/coupon_x.png',//新
			'j'=>'static/img/coupon_j.png',//减
    );
    
	/**
	 * 添加发送短信验证码记录
	 *
	 * @param	string	$mobile	手机号码
	 * @param	string	$code	编号
	 * @return	boolean
	 */
	public function addSmsCodeLog($mobile, $code){
	
		if( ! $mobile || ! $code){
			return false;
		}
	
		$data = array(
				'mobile' => $mobile,
				'code' => $code,
				'addtime' => time()
		);
	
		$this->db->where(array('mobile' => $mobile));
		$tI = $this->count($this->tbVerifyCode);
		$query = false;
		if($tI){
			$this->db->where(array('mobile' => $mobile));
			$query = $this->update($this->tbVerifyCode, $data);
		}else{
			$query = $this->insert($this->tbVerifyCode, $data);
		}

		if($query){
			return true;
		}
	
		return false;
	}
	
	/**
	 * 获取验证码发送日志
	 *
	 * @param	string	$mobile	手机号码
	 * @param	string	$code	验证码
	 * @return	array
	 */
	public function getSmsCodeLogInfo($mobile, $code = ''){
	
		if( ! $mobile){
			return array();
		}
	
		$this->db->where(array('mobile' => $mobile));
		if($code){
			$this->db->where(array('code' => $code));
		}
		$tA = $this->getOne($this->tbVerifyCode);
		if( ! $tA){
			return array();
		}
	
		return $tA;
	}
	
	/**
	 * 清空验证码
	 *
	 * @param	string	$mobile	手机号码
	 * @return	boolean
	 */
	public function deleteSmsCode($mobile){
	
		if( ! $mobile) return false;
		$this->db->where(array('mobile' => $mobile));
		if($this->update($this->tbVerifyCode, array('code' => ''))){
			return true;
		}
	
		return false;
	}
	
	/**
	 * 判断电话号码是否存在
	 *
	 * @param	string	$mobile	//手机号码
	 * @return	boolean (false:不存在   true:存在)
	 */
	public function mobileIsExist($mobile, $notId = 0){
			
		if( ! $mobile) return false;
		$this->db->select('id')->where(array('mobile' => $mobile));
		if($notId){
			$this->db->where(array('id <>' => $notId));
		}
		$this->db->where(array('status >' => 0));
		$tA = $this->getOne($this->tbUser);
		if($tA){
			return $tA['id'];
		}
			
		return false;
	}
	
	/**
	 * 添加登录信息
	 * 
	 * @param	integer	$userId		用户id
	 * @param	string	$sessionid	会话id
	 * @param	integer	$type		会话客服端类型（1:手机客户端  2: pc端）
	 * @return	boolean
	 */
	public function addSession($userId, $sessionid, $type = 1){
		
		$data = array(
					'merchant_id' => $userId,
					'sessionid' => $sessionid,
					'type' => $type,
					'addtime' => time(),
				);
				
		$this->db->where(array('merchant_id' => $userId, 'type' => $type));
		$tI = $this->count($this->tbSession);
		if($tI){
			$this->db->where(array('merchant_id' => $userId, 'type' => $type));
			if($this->update($this->tbSession, $data)){
				return true;
			}
		}else{
			if($this->insert($this->tbSession, $data)){
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * 删除sessionid
	 * @param 	integer $userId
	 * @param 	number 	$type
	 * @return	boolean
	 */
	public function deleteSession($userId, $type = 1){
		$this->db->where(array('merchant_id' => $userId, 'type' => $type));
		return $this->delete($this->tbSession);
	}

 	/**
 	 * 获取用户信息
 	 * 
 	 * @param	string	$mobile		手机号码
 	 * @param	string	$password	密码
     * @return array
 	 */
 	public function getInfoByMobileAndPassword($mobile, $password){

 		if( ! $mobile || ! $password){
 			return array();
 		}

 		$this->db->select('id,status,jpush_code,easemob_code,easemob_pwd')
 				 ->where(array('mobile' => $mobile, 'password' => $password, 'status >' => 0));
 		$tA = $this->getOne($this->tbUser);
 		if(empty($tA)) $tA = array();
 		return $tA;
 	}

    /**
     * 获取用户信息
     *
     * @param	int	$id		商户id
     * @param	string	$password	提现密码
     * @return array
     */
    public function getInfoByIdAndWithdrawPassword($merchantId, $password){

        if( ! $merchantId || ! $password){
            return array();
        }

        $this->db->select('id,status,jpush_code')
            ->where(array('id' => $merchantId, 'withdraw_password' => $password));
        $tA = $this->getOne($this->tbUser);
        if(empty($tA)) $tA = array();
        return $tA;
    }

    /**
     * 获取用户信息通过session
     *
     * @param	string 	$sessionid	会话id
     * @param	integer $type	(1：app 2：pc)
     * @return	array
     * @author khj
     */
    public function getInfoBySessionid($sessionid, $type = 1){

        if( ! $sessionid){
            return array();
        }
        $this->db->select('u.id,u.portrait,u.balance,u.rank,u.mobile,u.status,u.jpush_code,s.category_id')
            ->join($this->tbUser.' u', 'u.id = se.merchant_id')
            ->join($this->tbShop.' s', 's.merchant_id = se.merchant_id','left')
            ->where(array('se.sessionid' => $sessionid, 'se.type' => $type));

        $tA = $this->getOne($this->tbSession.' se');
        if( ! $tA){
            return array();
        }
        return $tA;
    }

    /**
     * 关键字搜索商家
     * @param $keyword      关键字
     * @param array $ci
     * @return array
     * @author zyl
     */
 	public function getInfoByLikeName($keyword, $ci = array()){
 		if (! $keyword){
 			return array();
 		}
        if (!empty($ci)){
            $this->db->where_in('county', $ci);
        }
 		$this->db->select('u.id,s.shop_name as name')
            ->join($this->tbShop.' s', 's.merchant_id = u.id')
            ->where(array('s.status' => 2, 'u.status >' => 0))
            ->where('(s.shop_name like "%'.$keyword.'%" or u.mobile like "%'.$keyword.'%")');
 		  return $this->getAll($this->tbUser.' u');

 	}

    /**
     * 区域获取商家
     * @param $ci
     * @return array
     */
    public function getInfoByCounty($ci){
        if (empty($ci)){
            return array();
        }

        $this->db->select('u.id,s.shop_name as name')
            ->join($this->tbShop.' s', 's.merchant_id = u.id')
            ->where_in('s.county', $ci)
            ->where(array('u.status >' => 0));
        $data = $this->getAll($this->tbUser.' u');
        $ids = array();
        foreach ($data as $v){
            $ids[] = $v['id'];
        }
        return $ids;
    }

    /**
     * 获取状态
     *
     * @param	integer	$key
     * @param	boolean	$show	是否显示
     * @return	mixed
     */
    public function getStatus($key = null, $show = false){

        $config = array(
            1 => '已禁用',
            2 => '使用中',
        );

        if($key !== null){

            if(isset($config[$key]) && ! $show){
                return $config[$key];
            }

            if(isset($config[$key]) && $show){

                if($key == 1){
                    return '<span class="label label-danger">'.$config[$key].'</span>';
                }else if($key == 2){
                    return '<span class="label label-success">'.$config[$key].'</span>';
                }
            }
            return '';
        }

        return $config;
    }

    /**
     * 店铺状态
     * @param null $key
     * @param bool $show
     * @return array|mixed|string
     */
    public function getShopStatus($key = null, $show = false){
        $config = $this->config['shop_status'];
        if($key !== null){

            if(isset($config[$key]) && ! $show){
                return $config[$key];
            }

            if(isset($config[$key]) && $show){

                if($key == 1){
                    return '<span class="label label-default">'.$config[$key].'</span>';
                }else if($key == 2){
                    return '<span class="label label-success">'.$config[$key].'</span>';
                }else if($key == 3){
                    return '<span class="label label-danger">'.$config[$key].'</span>';
                }
            }
            return '';
        }

        return $config;
    }

    /**
     * 置顶状态
     * @param null $key
     * @param bool $show
     * @return array|mixed|string
     */
    public function getTopStatus($key = null, $show = false){
        $config = array(1 => '普通', 2 => '置顶');
        if($key !== null){

            if(isset($config[$key]) && ! $show){
                return $config[$key];
            }

            if(isset($config[$key]) && $show){

                if($key == 1){
                    return '<span class="label label-success">'.$config[$key].'</span>';
                }else if($key == 2){
                    return '<span class="label label-danger">'.$config[$key].'</span>';
                }
            }
            return '';
        }

        return $config;
    }

    /**
     * 获取商家简单信息
     * @param unknown $merchantId
     * @return array
     */
    public function getMiniInfo($merchantId){
    	$this->db
    	->select("id,jpush_code")
    	->where('id',$merchantId);
    	return $this->getOne($this->tbUser);
    }
    
    /**
     * 获取商家简单信息
     * @param unknown $merchantId
     * @return array
     */
    public function getMiniInfoByIds($merchantIds){
    	$this->db
    	->select("id,auto_take,jpush_code")
    	->where_in('id',$merchantIds)
        ->where(array('status >' => 0));
    	$tA = $this->getAll($this->tbUser);
    	
    	$tData = array();
    	foreach ($tA as $k=>$v){
    		$tData[$v['id']] = $v;
    	}
    	return $tData;
    }
    
    /**
     * 获取商家信息
     * @param int   $merchantId 商家id
     * @param int   $countyId 区域id
     * @param bool $mini
     * @return array
     * @author khj
     */
    public function getInfo($merchantId, $countyId = 0, $mini = false){

        if(!$merchantId)return array();

        if($mini){

            $this->db->select('u.id,u.mobile,u.portrait,u.balance,u.business,u.withdraw_password,u.jpush_code,u.rank,
            u.honest,u.shop_imgs,u.shop_ads,u.shipping_type,u.is_top,s.other_documents,
                    u.score,s.shop_name,s.reason,s.status as shop_status,supervise,u.rank,u.percent,s.county')
                     ->join($this->tbShop.' s', 'u.id = s.merchant_id','left')
                     ->where('u.id', $merchantId);
            $tA = $this->getOne($this->tbUser.' u');
            if($tA){
                $tA['shop_name'] = $tA['shop_name'] ? $tA['shop_name']:'';
                $tA['shop_status'] = $tA['shop_status'] ? $tA['shop_status']:'0';
                $tA['score'] = $tA['score'] ? $tA['score']:'0';
                $tA['county'] = $tA['county'] ? $tA['county']:'0';
                $tA['percent'] = $tA['percent'] ? $tA['percent']:'0';
                $tA['reason'] = $tA['reason'] ? $tA['reason']:'';
                $tA['shop_imgs'] = $tA['shop_imgs'] ? json_decode($tA['shop_imgs'], true):array();
                $tA['other_documents'] = $tA['other_documents'] ? json_decode($tA['other_documents'], true):array();
                $tA['shop_ads'] = $tA['shop_ads'] ? json_decode($tA['shop_ads'], true):array();
                $tA['withdraw_password'] = $tA['withdraw_password'] ? 2:1;//提现密码：2已设置 1未设置
                $tA['portrait'] = $tA['portrait'] ? getImage($tA['portrait'],'og') : getDefaultPortrait(2);
                $tA['supervise'] = $tA['supervise']? json_decode($tA['supervise'],true ): array();

            }

            return $tA;
        }
    	$this->db
    	->select('u.id,u.balance,u.honest,u.min_consume,u.first_order_reduce,u.supervise,u.business,u.store_tel,u.score,u.jpush_code,
    	         u.business_week,u.rank,u.percent,u.shop_video,u.shipping_type,u.expect_arrive_time,shop.county,shop.other_documents,
				u.able_use_coupon,u.able_cash_coupon,u.portrait,u.mobile,u.gender,u.status,u.addtime,u.min_order_web_amount,shop.shop_name')
				->join($this->tbShop.' shop','u.id = shop.merchant_id','left')
    	->where('u.id',$merchantId);

    	$tA = $this->getOne($this->tbUser.' u');

        if($tA){
            $tA['portrait'] = $tA['portrait']? getImage($tA['portrait'], 'og'): getDefaultPortrait(2);
            $tA['gender'] = $tA['gender'] ? $this->config['gender'][$tA['gender']] : '保密';
            $tA['balance'] = $tA['balance'] ? $tA['balance'] : '0.00';
//            $tA['business_time_start'] = $tA['business_time_start'] ? time_to_second($tA['business_time_start'], true) : '';
//            $tA['business_time_end'] = $tA['business_time_end'] ? time_to_second($tA['business_time_end'], true) : '';
            $tA['business_week'] = $tA['business_week']?array_filter(explode(',',$tA['business_week'])):array();
            $supervise = $tA['supervise']? json_decode($tA['supervise'],true ): array();
            $tA['other_documents'] = $tA['other_documents'] ? json_decode($tA['other_documents'], true):array();
            if (!empty($supervise)){
                foreach ($supervise as $k => $v){
                    $supervise[$k]['supervise_man_portrait'] = getImage($v['supervise_man_portrait'], 'xs');
                    $supervise[$k]['supervise_woman_portrait'] = getImage($v['supervise_woman_portrait'], 'xs');
                }
            }
            $tA['supervise'] = $supervise;
            $tA['rank_name'] = $this->config['rank'][$tA['rank']];
            $tA['shop_video'] = $tA['shop_video']?base_url($tA['shop_video']):'';
        }

    	return $tA;
    }

    /**
     * 获取商家信息
     * @param $merchantIds  商家id
     * @return array
     */
    public function getInfoByIds($merchantIds){
    	if ( ! $merchantIds){
    		return array();
    	}

    	$this->db->select('u.id,u.mobile,u.business,u.business_week,u.store_tel,u.category_id,s.shop_type,u.portrait,u.percent,u.first_order_reduce,
							u.able_use_coupon,u.able_cash_coupon,u.status,u.jpush_code,IFNULL(u.min_consume,0) as min_consume,
							s.shop_name,u.shipping_type,s.latitude,s.longitude,s.address,u.shipping_type,u.expect_arrive_time,u.min_order_web_amount')
				 ->join($this->tbShop.' s','u.id = s.merchant_id','left')
				 ->where_in('u.id',$merchantIds);
				
		$tA = $this->getAll($this->tbUser.' u');
		
		$data = array();
		$d = getDefaultPortrait(2);
		foreach ($tA as $k=>&$v){
			$v['portrait'] = $v['portrait']?getImage($v['portrait']):array(
			    'og' => $d,
			    'sm' => $d,
			    'xs' => $d,
            );
			$data[$v['id']] = $v;
		}
		
		return $data;
    }

    /**
     * 首页搜索：通过关键词搜索店铺
     * @param $keyword   //关键词
     * @param $latitude  //坐标
     * @param $longitude //坐标
     * @return array
     */
    public function searchShopByKeyword($keyword, $latitude, $longitude){
        if(!$keyword)return array();

        get_instance()->loadModel('AdmSettingModel', 'mSetting','admin');
        //商家接单范围
        $merchant_distance = $this->mSetting->get('merchant_distance_limit');

        get_instance()->loadModel('ConsumerProductModel','mProduct','consumer');
        $this->db->like('shop.shop_name',$keyword);

        //距离的Sql
        $distance = ', 10000 as distance';
        if ($latitude && $longitude){

            $distance = ',if(shop.longitude > 0 and  shop.latitude, ( ( ACOS(SIN(('.$latitude.' * 3.1415) / 180 ) *SIN((shop.latitude * 3.1415) / 180 )
    			+ COS((' .$latitude.' * 3.1415) / 180 ) * COS((shop.latitude * 3.1415) / 180 ) * COS((' .$longitude.
                ' * 3.1415) / 180 - (shop.longitude * 3.1415) / 180 ) ) * 6378.138) * 1000), 10000) as distance';
        }
        //搜索店铺
        $this->db->select('u.id,shop.shop_name,shop.address,'.$distance)
            ->join($this->tbShop.' shop','u.id = shop.merchant_id')			//可查询商家名称
            ->join($this->mProduct->tbProduct.' p','p.merchant_id = u.id')	//可查看商家的商品
            ->group_by('p.merchant_id') // 按商品中的商家分组
            ->where('shop.status',2)//认证状态
            ->where('u.status',2)//商家状态
			->having('distance <', $merchant_distance*1000);
        $tA = $this->getAll($this->tbUser.' u');
        foreach ($tA as $k=>&$v){
            if($v['distance'] < 1000){
                $v['distance'] = round($v['distance'], 1).'m';
            }else{
                $v['distance'] = round($v['distance']/1000, 1).'km';
            }
        }
        return $tA;
    }

    /**
     * 首页搜索：通过关键词搜索商品
     * @param $keyword   //关键词
     * @param $latitude  //坐标
     * @param $longitude //坐标
     * @return array
     */
    public function searchProductByKeyword($keyword, $latitude, $longitude, $merchantId = 0){
        if(!$keyword)return array();

        get_instance()->loadModel('AdmSettingModel', 'mSetting','admin');
        //商家接单范围
        $merchant_distance = $this->mSetting->get('merchant_distance_limit');

        get_instance()->loadModel('ConsumerProductModel','mProduct','consumer');
        $this->db->like('p.name',$keyword);

        //距离的Sql
        $distance = ', 10000 as distance';
        if ($latitude && $longitude){

            $distance = ',if(shop.longitude > 0 and  shop.latitude, ( ( ACOS(SIN(('.$latitude.' * 3.1415) / 180 ) *SIN((shop.latitude * 3.1415) / 180 )
    			+ COS((' .$latitude.' * 3.1415) / 180 ) * COS((shop.latitude * 3.1415) / 180 ) * COS((' .$longitude.
                ' * 3.1415) / 180 - (shop.longitude * 3.1415) / 180 ) ) * 6378.138) * 1000), 10000) as distance';
        }
        //搜索商品
//        $this->db->or_like('p.name',$keyword);
        if ($merchantId){
            // 搜索某个店铺里面的商品
            $this->db->where('p.merchant_id', $merchantId);
        }
        $this->db->select('p.id,u.id as shop_id,shop.shop_name,p.name,'.$distance)
            ->join($this->tbShop.' shop','u.id = shop.merchant_id')			//可查询商家名称
            ->join($this->mProduct->tbProduct.' p','p.merchant_id = u.id')	//可查看商家的商品
            ->group_by('p.id') // 按商品分组
            ->where('shop.status',2)//认证状态
            ->where('u.status',2)
            ->where('p.status',2)//商家状态
			->having('distance <', $merchant_distance*1000);
        $tA = $this->getAll($this->tbUser.' u');
        foreach ($tA as $k=>&$v){
            if($v['distance'] < 1000){
                $v['distance'] = round($v['distance'], 1).'m';
            }else{
                $v['distance'] = round($v['distance']/1000, 1).'km';
            }
        }
        return $tA;
    }
    /**
     * APP获取商家列表
     * @param integer   $categoryId 	分类 商品
     * @param integer   $sort		 	排序方式 [1-距离最近 2-销量 3-评分 4-分类]
     * @param integer   $business 	    状态 1-休息中 2-营业中
     * @param integer   $page 		    分页
     * @param array     $merchantIds 	根据商家ids 筛选[收藏用]
     * @param boolean   $source 		源数据
     * @param string    $keyword
     * @param int       $latitude
     * @param int       $longitude
     * @param int       $limit
     * @return array
     * @author zyl
     */
    public function appGetShopList_old($categoryId = 0, $sort = 0, $business = 0, $page = 1, $merchantIds = array(),
                                   $source = FALSE,$keyword = '',$latitude = 0,$longitude = 0,$limit = 0){
    	

    	/**
    	 * sql
    	 */
    	get_instance()->loadModel('ConsumerProductModel','mProduct','consumer');
        get_instance()->loadModel('AdmSettingModel', 'mSetting','admin');
    	if ($keyword){
    		$this->db->like('shop.shop_name',$keyword)->or_like('p.name',$keyword);
    	}
    	//商家接单范围
        $merchant_distance = $this->mSetting->get('merchant_distance_limit');
    	//距离的Sql
    	$distance = ', 10000 as distance';
    	if ($latitude && $longitude){
    		
    		$distance = ',if(shop.longitude > 0 and  shop.latitude, ( ( ACOS(SIN(('.$latitude.' * 3.1415) / 180 ) *SIN((shop.latitude * 3.1415) / 180 )
    			+ COS((' .$latitude.' * 3.1415) / 180 ) * COS((shop.latitude * 3.1415) / 180 ) * COS((' .$longitude.
                ' * 3.1415) / 180 - (shop.longitude * 3.1415) / 180 ) ) * 6378.138) * 1000), 10000) as distance';
    	}
    	//月销量
    	$month_sales = ',COUNT(distinct o.id) as month_total';
    	$this->db->select('u.id,u.business,shop.shop_name,u.honest,shop.shop_type,u.portrait,u.score,u.expect_arrive_time,
						,u.sale_quantity,u.first_order_reduce'.$distance.$month_sales)
				->join($this->tbBusiness.' b','u.id = b.merchant_id')			//营业时间
				->join($this->tbShop.' shop','u.id = shop.merchant_id')			//可查询商家名称
				->join($this->mProduct->tbProduct.' p','p.merchant_id = u.id')	//可查看商家的商品
				->join($this->mProduct->tbProductCustomCategory.' pcc','pcc.merchant_id = u.id') //可查看商家的上级分类
				->join($this->mProduct->tbCategory.' c','c.id = pcc.category_id') //可查看商家的上级分类
				->join($this->mProduct->tbOrder.' o','o.merchant_id = u.id AND o.status in (4,5) AND o.addtime >='.strtotime('- 30 day',time()),'left') //可查看商家的上级分类
				
				->group_by('p.merchant_id') // 按商品中的商家分组
				->where('shop.status',2)//认证状态
				->where('u.business',2)//营业中
				->where('u.status',2)//商家状态
				->having('distance <', $merchant_distance*1000)
                ->order_by('is_top desc');
    	
		//根据商家ids来筛选
		if ($merchantIds){
			$this->db->where_in('shop.merchant_id',$merchantIds);
		}
				
		//分类
		if ($categoryId){
			//product 商家的商品中，分类的id
//			$this->db->where('pcc.category_id',$categoryId)->or_where('c.parent_id',$categoryId);
            $this->db->where('(pcc.category_id='.$categoryId.' or c.parent_id='.$categoryId.')');
		}
		
		
		//排序规则//筛选
		$ShopSort = array(
				1=>'distance asc',
				2=>'month_total desc',
				3=>'u.score desc'
		);
		if (array_key_exists($sort,$ShopSort)){
			$this->db->order_by($ShopSort[$sort].',id desc');
		}elseif($sort == 4){
			//分类筛选
		}
		
//		if ($business == 1){
//			//休息中的
//			$this->db->where('b.business_time_start >', time_to_second(date('H:i:s')) );
//			$this->db->where('b.business_time_end <=', time_to_second(date('H:i:s')) );
//		}elseif($business == 2){
//			//营业中
//			$this->db->where('b.business_time_start <=', time_to_second(date('H:i:s')) );
//			$this->db->where('b.business_time_end >', time_to_second(date('H:i:s')) );
//		}
    	
		$tA = $this->appPage($this->tbUser.' u',$page,false,$limit);
	    //echo $this->db->last_query();
	    if ( ! $tA['list']){
	    	return array();
	    }
	    if ($source){
	    	//源数据
	    	return $tA;
	    }

	    /**
	     * 处理数据
	     */
	    $merchantIds = array();//商家ids
	    foreach ($tA['list'] as $k => $v){
	    	//获取商户ids
	    	if ( ! in_array($v['id'], $merchantIds)){
	    		$merchantIds[] = $v['id'];
	    	}
	    }

	    get_instance()->loadModel('ConsumerProductModel','mProduct','consumer');
	    get_instance()->loadModel('MerchantCommentModel','mComment','merchant');
	    //$tSales = $this->mProduct->getSaleQuantityByMonth($merchantIds);
	   //商家多时间段营业时间
        $this->db->select('merchant_id,business_time_start,business_time_end')
            ->where_in(array('merchant_id' => $merchantIds));
        $tBusiness = $this->getAll($this->tbBusiness);
        $merBus = [];
        if($tBusiness){
            foreach ($tBusiness as $bus){
                $merBus[$bus['merchant_id']][] = $bus;
            }
            unset($tBusiness);
        }
        $_for = getCustomConfig('expect_take_time');
        $_other = $this->mSetting->get('rob_expect_time', 'deliveryman');

        $time = time_to_second(date('H:i:s'));//当前时间换算秒
    	foreach ($tA['list'] as $k => $v){

    	    if(isset($merBus[$v['id']])){
    	        $times = $merBus[$v['id']];
    	        $v['expect_arrive_time'] = $v['expect_arrive_time'] ? $v['expect_arrive_time']:'0';
                $tA['list'][$k]['expect_arrive_time'] = $v['expect_arrive_time'];
                $addSecond = ($v['expect_arrive_time'] + $_for + $_other)*60;
//                $time = $time + $addSecond;

    	        foreach ($times as $kk=>$tt){
    	            if($tt['business_time_start'] == 0 && $tt['business_time_end'] == 0){
                        $tA['list'][$k]['business'] = 2;break;
                    }
                    elseif ($time < $tt['business_time_start'] || $time > $tt['business_time_end']){
                        $tA['list'][$k]['business'] = 1;
                    }else{
                        $tA['list'][$k]['business'] = 2;break;
                    }

                }
            }

    		//获取平均分
            $moren = getDefaultPortrait(2);
    		$tA['list'][$k]['headurl'] 	= $v['portrait']?getImage($v['portrait']):array('og'=>$moren,'xs'=>$moren,'sm'=>$moren);
    		$tA['list'][$k]['sale'] 	= $v['month_total'];
    		$tA['list'][$k]['score'] = $this->mComment->totalScore($v['id']);
    		$tA['list'][$k]['distance'] = (string)ceil($v['distance']);//距离 
    		$tA['list'][$k]['s_type'] = array(
    				'dian'=>$v['shop_type'] != 1 ? 2: 1,//到店
    				'song'=>$v['shop_type'] != 2 ? 2: 1,//送货上门
    				'cheng'=>empty($v['honest'])?'1':$v['honest'],
    		);
    		$tA['list'][$k]['honest'] = empty($v['honest'])?"1":$v['honest'];
    		unset($tA['list'][$k]['portrait']);
    		unset($tA['list'][$k]['sale_quantity']);
    		unset($tA['list'][$k]['business_time_start']);
    		unset($tA['list'][$k]['business_time_end']);
    	}
    	
    	/**
    	 * 获取代金劵
    	 * @var array $tPromotion
    	 */
    	$tPromotion = array();
    	$tFullCut = array();
    	if ($merchantIds){
	    	get_instance()->loadModel('MerchantPromotionModel','mPromotion','merchant');
            get_instance()->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

    		//代金劵
	    	$tPromotion = $this->mPromotion->getCouponListByMerchantIds($merchantIds);
	    	//满减劵
	    	$tFullCut = $this->mPromotion->getFullCutListByMerchantIds($merchantIds);

	    	foreach ($tA['list'] as $k=>$v){

                $rule = '';
	    		//满减劵
	    		if (isset($tFullCut[$v['id']]['rule'])){
	    			$full = json_decode($tFullCut[$v['id']]['rule'],true);
	    			if ( ! $full){
	    				$full = array();
	    			}

	    			foreach ($full as $fk=>$fv){
	    				if ($fv['max_money']){
		    				if ($rule){
		    					$rule .= ',';
		    				}

		    				$rule .= '满'.$fv['max_money'].'减配送费'.$fv['money'];
	    				}
	    			}
	    		}
	    		if ( ! empty($rule)){
		    		$tA['list'][$k]['note'][] =array('text'=>$rule,'icon'=>getImage($this->SHOP_ICON['j'],'sm'));
	    		}
                //代金劵
                if (isset($tPromotion[$v['id']])){
                    $tA['list'][$k]['note'][] = array('text'=>'下单即送代金劵','icon'=>getImage($this->SHOP_ICON['d'],'sm'));
                }

                // 首单减免
                if ($v['first_order_reduce'] > 0){
                    $tA['list'][$k]['note'][] = array('text'=>'首单减免'.$v['first_order_reduce'].'元','icon'=>getImage($this->SHOP_ICON['x'],'sm'));
                }
	    	}
    	}
    	
    	return $tA['list'];
    }
	
	public function appGetShopList($categoryId = 0, $sort = 0, $business = 0, $page = 1, $merchantIds = array(),
                                   $source = FALSE,$keyword = '',$latitude = 0,$longitude = 0,$limit = 0){


        /**
         * sql
         */
        get_instance()->loadModel('ConsumerProductModel','mProduct','consumer');
        get_instance()->loadModel('AdmSettingModel', 'mSetting','admin');
        if ($keyword){
            $this->db->like('shop.shop_name',$keyword)->or_like('p.name',$keyword);
        }
        //商家接单范围
        $merchant_distance = $this->mSetting->get('merchant_distance_limit');
        //距离的Sql
        $distance = ', 10000 as distance';
        if ($latitude && $longitude){

            $distance = ',if(shop.longitude > 0 and  shop.latitude, ( ( ACOS(SIN(('.$latitude.' * 3.1415) / 180 ) *SIN((shop.latitude * 3.1415) / 180 )
    			+ COS((' .$latitude.' * 3.1415) / 180 ) * COS((shop.latitude * 3.1415) / 180 ) * COS((' .$longitude.
                ' * 3.1415) / 180 - (shop.longitude * 3.1415) / 180 ) ) * 6378.138) * 1000), 10000) as distance';
        }
        //月销量
        $month_sales = ',COUNT(distinct o.id) as month_total';
        $this->db->select('u.id,u.business,shop.shop_name,u.honest,shop.shop_type,u.portrait,u.score,u.expect_arrive_time,
						,u.sale_quantity,u.first_order_reduce'.$distance.$month_sales)
//            ->join($this->tbBusiness.' b','u.id = b.merchant_id')			//营业时间
            ->join($this->tbShop.' shop','u.id = shop.merchant_id')			//可查询商家名称
//            ->join($this->mProduct->tbProduct.' p','p.merchant_id = u.id')	//可查看商家的商品
            ->join($this->mProduct->tbProductCustomCategory.' pcc','pcc.merchant_id = u.id') //可查看商家的上级分类
            ->join($this->mProduct->tbCategory.' c','c.id = pcc.category_id') //可查看商家的上级分类
            ->join($this->mProduct->tbOrder.' o','o.merchant_id = u.id AND o.status in (4,5) AND o.addtime >='.strtotime('- 30 day',time()),'left') //可查看商家的上级分类

//            ->group_by('p.merchant_id') // 按商品中的商家分组
            ->group_by('shop.merchant_id') // 按认证中的商家分组
            ->where('shop.status',2)//认证状态
            ->where_in('u.business', array(1,2))//营业中
            ->where('u.status',2)//商家状态
            ->having('distance <', $merchant_distance*1000);

        //根据商家ids来筛选
        if ($merchantIds){
            $this->db->where_in('shop.merchant_id',$merchantIds);
        }

        //分类
        if ($categoryId){
            //product 商家的商品中，分类的id
//			$this->db->where('pcc.category_id',$categoryId)->or_where('c.parent_id',$categoryId);
            $this->db->where('(pcc.category_id='.$categoryId.' or c.parent_id='.$categoryId.')');
        }


        //排序规则//筛选
        $ShopSort = array(
            1=>'distance asc',
            2=>'month_total desc',
            3=>'u.score desc'
        );
        if (array_key_exists($sort,$ShopSort)){
            $this->db->order_by($ShopSort[$sort].',id desc');
        }elseif($sort == 4){
            //分类筛选
        }else{
            $this->db->order_by('is_top desc,id desc');
        }


        $tA = $this->appPage($this->tbUser.' u',$page,false,$limit);
//echo  $this->db->last_query();
        if ( ! $tA['list']){
            return array();
        }
        if ($source){
            //源数据
            return $tA;
        }

        /**
         * 处理数据
         */
        $merchantIds = array();//商家ids
        foreach ($tA['list'] as $k => $v){
            //获取商户ids
            if ( ! in_array($v['id'], $merchantIds)){
                $merchantIds[] = $v['id'];
            }
        }

        $time = time_to_second(date('H:i:s'));//当前时间换算秒
        foreach ($tA['list'] as $k => $v){

            //获取平均分
            $moren = getDefaultPortrait(2);
            $tA['list'][$k]['headurl'] 	= $v['portrait']?getImage($v['portrait']):array('og'=>$moren,'xs'=>$moren,'sm'=>$moren);
            $tA['list'][$k]['sale'] 	=  $v['month_total'];
            $tA['list'][$k]['score'] = $v['score'];
            $tA['list'][$k]['distance'] = (string)ceil($v['distance']);//距离
            $tA['list'][$k]['s_type'] = array(
                'dian'=>$v['shop_type'] != 1 ? 2: 1,//到店
                'song'=>$v['shop_type'] != 2 ? 2: 1,//送货上门
                'cheng'=>empty($v['honest'])?'1':$v['honest'],
            );
            $tA['list'][$k]['honest'] = empty($v['honest'])?"1":$v['honest'];
            unset($tA['list'][$k]['portrait']);
            unset($tA['list'][$k]['sale_quantity']);

        }

        /**
         * 获取代金劵
         * @var array $tPromotion
         */
        $tPromotion = array();
        $tFullCut = array();
        if ($merchantIds){
            get_instance()->loadModel('MerchantPromotionModel','mPromotion','merchant');
            get_instance()->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

            //代金劵
            $tPromotion = $this->mPromotion->getCouponListByMerchantIds($merchantIds);
            //满减劵
            $tFullCut = $this->mPromotion->getFullCutListByMerchantIds($merchantIds);
            //获取商家30天内销量
//            $tSale = $this->mOrder->getMonthSaleCount($merchantIds);
            $merchantBusiness = $this->getBusinessMerchant($merchantIds);
            //商家多时间段营业时间
            $this->db->select('merchant_id,business_time_start,business_time_end')
                ->where_in(array('merchant_id' => $merchantIds));
            $tBusiness = $this->getAll($this->tbBusiness);
            $merBus = [];

            if($tBusiness){
                foreach ($tBusiness as $bus){

                    $merBus[$bus['merchant_id']][] = $bus;
                }
                unset($tBusiness);
            }
            $_for = getCustomConfig('expect_take_time');
            $_other = $this->mSetting->get('rob_expect_time', 'deliveryman');

            foreach ($tA['list'] as $k=>$v){
                //送达时间
                $_time = isset($merBus[$v['id']])?$merBus[$v['id']]:array();
                $arriveTime = appArriveTime($_time,0,0,0,20);
                $expectArriveTime = '';
                if($v['business'] == 2 && $_time && !isset($merchantBusiness[$v['id']])){

                    if($arriveTime['today']){
                        $expectArriveTime = $arriveTime['today'][0].'起送';
                    }elseif ($arriveTime['other']){
                        $expectArriveTime = '明日'.$arriveTime['other'][0].'起送';
                    }
                }

                $tA['list'][$k]['business_desc'] = $expectArriveTime;

                //销量
//                $tA['list'][$k]['sale'] = isset($tSale[$v['id']])?$tSale[$v['id']]:0;

                $rule = '';
                //满减劵
                if (isset($tFullCut[$v['id']]['rule'])){
                    $full = json_decode($tFullCut[$v['id']]['rule'],true);
                    if ( ! $full){
                        $full = array();
                    }

                    foreach ($full as $fk=>$fv){
                        if ($fv['max_money']){
                            if ($rule){
                                $rule .= ',';
                            }

                            $rule .= '满'.$fv['max_money'].'减配送费'.$fv['money'];
                        }
                    }
                }
                $tA['list'][$k]['note'] = array();
                if ( ! empty($rule)){
                    $tA['list'][$k]['note'][] =array('text'=>$rule,'icon'=>getImage($this->SHOP_ICON['j'],'sm'));
                }
                //代金劵
                if (isset($tPromotion[$v['id']])){
                    $tA['list'][$k]['note'][] = array('text'=>'下单即送代金劵','icon'=>getImage($this->SHOP_ICON['d'],'sm'));
                }

                // 首单减免
                if ($v['first_order_reduce'] > 0){
                    $tA['list'][$k]['note'][] = array('text'=>'首单减免'.$v['first_order_reduce'].'元','icon'=>getImage($this->SHOP_ICON['x'],'sm'));
                }
            }
        }

        return $tA['list'];
    }

    /**
     * 保存用户信息
     *
     * @param	array	$data	保存数据
     * @param	integer $id		用户id
     * @return	boolean
     */
    public function save($data, $id = 0){
    	
    	if( ! $data) return false;
    	if($id){
    		$this->db->where(array('id' => $id));
    		if($this->update($this->tbUser, $data)){
    			return true;
    		}
    	}else{
    		if($id = $this->insert($this->tbUser, $data)){
    			return $id;
    		}
    	}
    }

    /**
     * 保存商家升级记录
     * @param $data
     * @return bool|int
     * @author heyu
     */
    public function saveRankLog($data){
        if( ! $data) return false;
        return $this->insert($this->tbRankLog, $data);
    }

    /**
     * 获取商家升级记录
     * @param $merchantId
     * @return array
     */
    public function getRankList($merchantId){
        if (!$merchantId){
            return array();
        }
        $this->db->where(array('merchant_id' => $merchantId));
        $list = $this->getAll($this->tbRankLog);
        foreach ($list as $k => &$v){
            $v['rank_name'] = $this->config['rank'][$v['rank']];
            $v['addtime'] = dateFormat($v['addtime']);
        }
        return $list;
    }

    /**
     * 清空多时段设置
     * @param $merchantId
     * @return bool
     * @author heyu
     */
    public function deleteBusinessTime($merchantId){
        if (!$merchantId){
            return false;
        }
        $this->db->where(array('merchant_id' => $merchantId));
        return $this->delete($this->tbBusiness);
    }

    /**
     * 批量保存多时间段
     * @param $data
     * @return bool
     * @author heyu
     */
    public function saveBusinessTime($data){
        if( ! $data) return false;
        return $this->insertBatch($this->tbBusiness, $data);
    }

    /**
     * 获取多时间段信息
     * @param $merchantId
     * @return array
     * @author heyu
     */
    public function getBusinessTimeList($merchantId,$min = false){
        if (!$merchantId){
            return array();
        }
        $this->db->select('business_time_start,business_time_end')
                 ->where(array('merchant_id' => $merchantId));
        $tA = $this->getAll($this->tbBusiness);

        if ( ! $tA){
            //如果没有 默认全天 zyl
            $tA = array(
                array(
                    'business_time_start'=>0,
                    'business_time_end'=>86400,
                )
            );
        }

        if ($min){
            return $tA;
        }

        foreach ($tA as $k => $v){
            $tA[$k]['business_time_start'] = time_to_second($v['business_time_start'], true);
            $tA[$k]['business_time_end'] = time_to_second($v['business_time_end'], true);
        }
        return $tA;
    }

    /////////////////////////////////////////////////////////////////
    //+-------------------------------------------------------------
    //|	商家认证
    //+-------------------------------------------------------------

    /**
     * 获取店铺类型
     * @return array
     * @author khj
     */
    public function getMerchantCategory($status = 2){

        $this->db->select('id,name')
        		 ->order_by('id desc');
        if($status){
        	$this->db->where('status', $status);
        }

        return $this->getAll($this->tbCat);
    }

    /**
     * 保存用户店铺信息
     * @param	array	$data	保存数据
     * @param	integer $id		用户id
     * @return	boolean
     * @author khj
     */
    public function saveShop($data, $id = 0){
    	
    	if( ! $data) return false;
    	if($id){
    		$this->db->where(array('merchant_id' => $id));
    		if($this->update($this->tbShop, $data)){
    			return true;
    		}
    	}else{
    		if($id = $this->insert($this->tbShop, $data)){
    			return $id;
    		}
    	}
    }

    /**
     * 获取认证信息
     * @param $merchantId   int    商户id
     * @param $mini         bool
     * @return array
     * @author khj zyl
     */
    public function getShopInfo($merchantId,$mini = FALSE, $is_merchant = false){

        if(!$merchantId)return array();
		
		$select = "s.merchant_id,u.honest,u.rank,s.shop_name,s.shop_type,u.min_consume,s.province,s.city,
					s.county,s.longitude,s.latitude,s.address,s.street,s.category_id,
					s.id_name,s.identification,s.license,s.addtime,s.status,u.supervise,u.jpush_code";
		
		$select .= ",u.mobile,u.store_tel,u.portrait,u.sale_quantity,u.score,u.business_week,u.auto_take,
		              u.business,u.shop_video,u.shop_imgs,u.shop_ads,u.expect_arrive_time,
		              u.shipping_type,u.first_order_reduce,s.other_documents";//店铺信息[zyl]
		
		$this->db->select($select)
            ->join($this->tbUser.' u','u.id = s.merchant_id')
            ->where('s.merchant_id',$merchantId);
        $tA = $this->getOne($this->tbShop.' s');
        
		if ( ! $tA){
			return array();
		}
        //获取店铺营业时间
        $time = $this->getBusinessTimeList($merchantId);

        if($tA){
            get_instance()->loadModel('AdmSettingModel', 'mSetting','admin');
            $tLocation = $this->mSetting->getLocationNameByIds(array($tA['province'],$tA['city'],$tA['county']));

            $tA['province_name'] = isset($tLocation[$tA['province']]) ? $tLocation[$tA['province']]['name'] : '';
            $tA['city_name'] = isset($tLocation[$tA['city']]) ? $tLocation[$tA['city']]['name'] : '';
            $tA['county_name'] = isset($tLocation[$tA['county']]) ? $tLocation[$tA['county']]['name'] : '';
            $tA['address_desc'] = $tA['province_name'].$tA['city_name'].$tA['county_name'].$tA['address'].$tA['street'];
            $tA['status_name'] = $this->config['shop_status'][$tA['status']];
            $tA['license'] = getImage($tA['license']);

            $tA['portrait'] = $tA['portrait']?getImage($tA['portrait'],'og'):getDefaultPortrait(2);
            $tA['shop_imgs'] = json_decode($tA['shop_imgs'],true);
            $tA['shop_ads'] = json_decode($tA['shop_ads'],true);
            $tA['other_documents'] = json_decode($tA['other_documents'],true);
            $tA['shop_type_name'] = $this->config['shop_type'][$tA['shop_type']];
            if ($tA['shop_imgs']){
            	//图片存在则处理
            	foreach ($tA['shop_imgs'] as $k=>$v){
            		$tA['shop_imgs'][$k] = getImage($v,'og');

            	}
            }
            if ($tA['other_documents']){
                //图片存在则处理
                foreach ($tA['other_documents'] as $k=>$v){
                    $tA['other_documents'][$k] = getImage($v,'og');

                }
            }
            if ($tA['shop_ads']){
            	//图片存在则处理
            	foreach ($tA['shop_ads'] as $k=>$v){
            		if($is_merchant){
                        $tA['shop_ads'][$k] = getImage($v['adpic'],'og');
                    }else{
                        $tA['shop_ads'][$k]['adpic'] = getImage($v['adpic'],'og');
                    }
            	}
            }
//            //营业状态
//            if($tA['business'] == 2){
//                $_for = getCustomConfig('expect_take_time');
//                $_other = $this->mSetting->get('rob_expect_time', 'deliveryman');
//                $addSecond = ($tA['expect_arrive_time'] + $_for + $_other)*60;
//                $now = time_to_second(date('H:i:s')) + $addSecond;//当前时间换算秒
//                foreach ($time as $tt){
//                    $tt['business_time_start'] = time_to_second($tt['business_time_start']);
//                    $tt['business_time_end'] = time_to_second($tt['business_time_end']);
//
//                    if($tt['business_time_start'] == 0 && $tt['business_time_end'] == 0){
//                        $tA['business'] = 2;break;
//                    }
//                    elseif ($now < $tt['business_time_start'] || $now > $tt['business_time_end']){
//                        $tA['business'] = 1;
//                    }else{
//                        $tA['business'] = 2;break;
//                    }
//                }
//            }

        }

        get_instance()->loadModel('ConsumerProductModel','mProduct','consumer');
        
        get_instance()->loadModel('MerchantCommentModel','mComment','merchant');

        if ($mini){
        	//获取店铺详情
        	$tData['merchant'] = array(
        			'shop_name' 	=> $tA['shop_name'],
        			'auto_take' 	=> $tA['auto_take'],
        			'business' 	=> $tA['business'],
        			'portrait' 		=> $tA['portrait'],
        			'province' 		=> $tA['province'],
        			'city' 			=> $tA['city'],
        			'county' 		=> $tA['county'],
        			'min_consume' 	=> $tA['min_consume'],
        			'sale_quantity' => empty($tA['sale_quantity']) ? '0' : $tA['sale_quantity'],
        			'address' 		=> $tA['street'],
        			'score' 		=> $this->mComment->totalScore($merchantId),
        			'cheng' 		=> empty($tA['honest'])?"1":$tA['honest'],
        			'rank' 			=> empty($tA['rank'])?"1":$tA['rank'],//1初级 2中级 3高级',
        			'shop_video' 	=> $tA['shop_video']?base_url($tA['shop_video']):'',
        			'merchant_easemob'=>$tA['jpush_code'],
        			'total_product' => (string)$this->mProduct->getTotalProductByMerchantId($merchantId),
        			'longitude' 	=> empty($tA['longitude'])?"0":$tA['longitude'],
        			'latitude' 		=> empty($tA['latitude'])?"0":$tA['latitude'],
        	);

        	$tData['profile'] = array(
        			'business_time'=>$time,
        			'business_week'=>$tA['business_week'],
        			'business'=>$tA['business'],
        			'mobile'=>$tA['store_tel']?$tA['store_tel']:'',
        			'shop_type'=>$tA['shop_type'],
        			'shipping_type'=>$tA['shipping_type'],
        			'expect_arrive_time'=>$tA['expect_arrive_time'],
        			'license'=>$tA['license'],
        			'first_order_reduce'=>$tA['first_order_reduce'],
        			's_type' => array(
        					'dian'=>$tA['shop_type'] != 1 ? 2: 1,
        					'song'=>$tA['shop_type'] != 2 ? 2: 1,
        					'cheng'=>empty($tA['honest'])?'1':$tA['honest'],
        			),
        			'shop_imgs'=>empty($tA['shop_imgs'])? array() : $tA['shop_imgs'],
        			'shop_ads'=>empty($tA['shop_ads'])? array() : $tA['shop_ads']
        	);
        	
        	$tData['supervise'] = empty(json_decode($tA['supervise'],true))?array():json_decode($tA['supervise'],true);
        	foreach ($tData['supervise'] as $k=>&$v){
        		
        		$v['supervise_man_portrait'] = getImage($v['supervise_man_portrait'],'og');
        		$v['supervise_woman_portrait'] = getImage($v['supervise_woman_portrait'],'og');
        	}
        	
        	return $tData;
        }
        return $tA;
    }

    /**
     * 统计已认证商家
     * @param $time     int     当月新增消费者
     * @param $ci       array   区域
     * @return array
     * @author heyu
     */
    public function getTotalMerchantShop($time = 0, $ci = array()){
         if ($time){
            $this->db->where('s.addtime > '.$time);
        }
        if (!empty($ci)){
            $this->db->where_in('s.county', $ci);
        }
        $this->db
                ->join($this->tbUser.' u',' on u.id = s.merchant_id')
                ->where('s.status', 2)
                ->where(array('u.status >' => 0));
				
        return $this->count($this->tbShop.' s');
    }
	
	

    /////////////////////////////////////////////////////////////////
    //+-------------------------------------------------------------
    //|	后台方法
    //+-------------------------------------------------------------
    /**
     * @param array $ci
     * @return array
     */
    public function adminGetList($ci = array()){
        if (!empty($ci)){
            $this->db->where_in('shop.county', $ci);
        }

        $rank = trim(get('rank'));
        $shopName = trim(get('shop_name'));
        $mobile = trim(get('mobile'));
        $addTimeFrom = strtotime(get('add_time_from'));
        $addTimeTo = strtotime(get('add_time_to'));
        $shopAddTimeFrom = strtotime(get('shop_add_time_from'));
        $shopAddTimeTo = strtotime(get('shop_add_time_to'));
        $status = (int)get('status');
        $business = (int)get('business');
        $shopStatus = trim(get('shop_status'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"


        if ($shopName){
            $this->db->like(array('shop.shop_name' => $shopName));
        }
        if ($mobile){
            $this->db->like(array('u.mobile' => $mobile));
        }
        if($addTimeFrom){
            $this->db->where('u.addtime >=', $addTimeFrom);
        }
        if($addTimeTo){
            $this->db->where('u.addtime <= ', strtotime('+1day', $addTimeTo));
        }
        if($shopAddTimeFrom){
            $this->db->where('shop.addtime >=', $shopAddTimeFrom);
        }
        if($shopAddTimeTo){
            $this->db->where('shop.addtime <= ', strtotime('+1day', $shopAddTimeTo));
        }
        if ($status){
            $this->db->where(array('u.status' => $status));
        }
        if ($rank){
            $this->db->where(array('u.rank' => $rank));
        }
        if ($business){
            $this->db->where(array('u.business' => $business));
        }
        if ($shopStatus){
            $this->db->where(array('shop.status' => $shopStatus));
        }

        if($iSortCol_0 == 3){
            $this->db->order_by('u.balance '.$sSortDir_0); // 余额
        }elseif ($iSortCol_0 == 4){
            $this->db->order_by('u.percent '.$sSortDir_0); // 平台比例
        }elseif ($iSortCol_0 == 5){
            $this->db->order_by('u.score '.$sSortDir_0); // 评分
        }elseif ($iSortCol_0 == 6){
            $this->db->order_by('u.addtime '.$sSortDir_0); // 注册时间
        }elseif ($iSortCol_0 == 7){
            $this->db->order_by('shop.addtime '.$sSortDir_0); // 认证时间
        }else{
            $this->db->order_by('shop.addtime desc'); // 认证时间
        }

    	$this->db->select('u.id,u.portrait,u.mobile,u.balance,u.percent,u.score,u.rank,u.business,u.is_top,
							u.addtime,shop.shop_name,shop.addtime as shop_addtime,u.status,shop.status as shop_status,shop.reason')
    			 ->join($this->tbShop.' shop','u.id = shop.merchant_id','left')
                 ->where(array('u.status >' => 0));
    	return $this->pagination($this->tbUser.' u');
    }

    /**
     * 商户认证申请
     * @param bool  $isCount
     * @param array $ci
     * @return array
     */
    public function getMerchantAuthenticationList($isCount = false,$ci = array()){
        $shop_name = trim(get('shop_name'));
        $mobile = trim(get('mobile'));
        $shop_type = (int)get('shop_type');
        $id_name = trim(get('id_name'));
        $identification = trim(get('identification'));
        $shop_status = (int)get('shop_status');
        $send_date_from = get('send_date_from');
        $send_date_to = get('send_date_to');
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($shop_name){
            $this->db->like(array('u.shop_name' => $shop_name));
        }
        if ($mobile){
            $this->db->like(array('u.mobile' => $mobile));
        }
        if ($shop_type){
            $this->db->where(array('s.shop_type' => $shop_type));
        }
        if ($id_name){
            $this->db->like(array('s.id_name' => $id_name));
        }
        if ($identification){
            $this->db->like(array('s.identification' => $identification));
        }
        if ($shop_status){
            $this->db->where(array('s.status' => $shop_status));
        }
        if (strlen($send_date_from) && strlen($send_date_to)){
            $this->db->where(array('u.addtime >= ' => strtotime($send_date_from), 'u.addtime <= ' => strtotime($send_date_to)));
        }
        if ($iSortCol_0 == 6){
            $this->db->order_by('s.addtime '.$sSortDir_0); // 认证时间
        }
        if (!empty($ci)){
            $this->db->where_in('s.county', $ci);
        }

        $this->db->select('u.id,u.portrait,u.mobile,s.shop_name,s.addtime as shop_addtime,
            s.status as shop_status,s.shop_type,s.province,s.city,s.county,s.address,s.street,s.id_name,s.identification')
            ->join($this->tbShop.' s','u.id = s.merchant_id')
            ->where(array('s.status' => 3, ' u.status >' => 0));
        if ($isCount){
            return $this->count($this->tbUser.' u');
        }
        $data = $this->pagination($this->tbUser.' u');

        if (!empty($data['data'])){
            $tLocationIds = array();
            foreach ($data['data'] as $k =>$v){
                if (!in_array($v['province'], $tLocationIds)){
                    $tLocationIds[] = $v['province'];
                }
                if (!in_array($v['city'], $tLocationIds)){
                    $tLocationIds[] = $v['city'];
                }
                if (!in_array($v['county'], $tLocationIds)){
                    $tLocationIds[] = $v['county'];
                }
            }
            get_instance()->loadModel('AdmSettingModel', 'mSetting','admin');
            $tLocation = $this->mSetting->getLocationNameByIds($tLocationIds);
            if ($tLocation){
                foreach ($data['data'] as $k=>$v){
                    $data['data'][$k]['location'] = $tLocation[$v['province']]['name'].
                        $tLocation[$v['city']]['name'].
                        $tLocation[$v['county']]['name'].
                        $v['address'].$v['street'];
                }
            }
        }
        return $data;
    }

    /**
     * 监管部门获取数据
     * @return array
     * @author heyu
     */
    public function supervisePcGetList(){
        $shopName = trim(get('shop_name'));
        $honest = (int)get('honest');
        $province = (int)get('province');
        $city = (int)get('city');
        $county = (int)get('county');
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($shopName){
            $this->db->like(array('s.shop_name' => $shopName));
        }
        if ($honest){
            $this->db->where(array('u.honest' => $honest));
        }
        if ($province){
            $this->db->where(array('s.province' => $province));
        }
        if ($city){
            $this->db->where(array('s.city' => $city));
        }
        if ($county){
            $this->db->where(array('s.county' => $county));
        }
        if($iSortCol_0 == 2){
            $this->db->order_by('u.sale_quantity '.$sSortDir_0);
        }elseif ($iSortCol_0 == 3){
            $this->db->order_by('u.score '.$sSortDir_0);
        }else{
            $this->db->order_by('u.id desc');
        }
        $this->db->select('u.id,u.sale_quantity,u.score,u.honest,s.shop_name,s.province,s.city,s.county')
            ->join($this->tbShop.' s', 'u.id=s.merchant_id');
        $tA = $this->pagination($this->tbUser.' u');
        if (!empty($tA['data'])) {
            $ids = array();
            foreach ($tA['data'] as $k => $v) {
                if (!in_array($v['province'], $ids) && $v['province'] > 0){
                    $ids[] = $v['province'];
                }
                if (!in_array($v['city'], $ids) && $v['city'] > 0){
                    $ids[] = $v['city'];
                }
                if (!in_array($v['county'], $ids) && $v['county'] > 0){
                    $ids[] = $v['county'];
                }
            }
            get_instance()->loadModel('AdmSettingModel', 'mSetting', 'admin');
            $region = $this->mSetting->getLocationNameByIds($ids);

            foreach ($tA['data'] as $kk => $vv) {
                if (isset($region[$vv['province']]) && $region[$vv['city']] && $region[$vv['county']]){
                    $tA['data'][$kk]['region'] = $region[$vv['province']]['name'].'-'.$region[$vv['city']]['name'].'-'.$region[$vv['county']]['name'];
                }else{
                    $tA['data'][$kk]['region'] = '';
                }
            }
        }
        return $tA;
    }

    /**
     * 获取全部商家
     */
    public function getMerchantAll(){
        $this->db->select('m.id,s.shop_name')
            ->join($this->tbShop.' s', 's.merchant_id=m.id')
            ->where('m.status > 1');
        $data = $this->getAll($this->tbUser.' m');
        return $data;
    }

    /**
     * 获取营业时间段内的商家
     */
    public function getBusinessMerchant($merchantId = []){
        if($merchantId){
            $this->db->where_in('merchant_id', $merchantId);
        }
        $time = time_to_second(date('H:i:s')) - 60;//当前时间换算秒
        $this->db->select('merchant_id,business_time_start,business_time_end')
            ->where(array('business_time_start <= ' => $time, 'business_time_end > ' => $time))
            ->order_by('merchant_id asc');
        $tBusiness = $this->getAll($this->tbBusiness);

        $tData = array();
        foreach ($tBusiness as $k=>$v){

            $tData[$v['merchant_id']] = $v;
        }
        return $tData;
    }
}